using System;
using System.ComponentModel;
using MettleSystems.dashCommerce.Core;
using MettleSystems.dashCommerce.Store;
using OpenNetCommerce.Localization;

namespace MettleSystems.dashCommerce.Controls
{
	public class BasePage : System.Web.UI.Page
	{
		#region Member Variables

		//private SiteSettings _siteSettings;
		private string _localizedTitleKey;
		private bool _bypassTitleBuild = false;

		#endregion

		#region Properties

		/// <summary>
		/// Gets the site settings.
		/// </summary>
		/// <value>The site settings.</value>
		[Browsable(false)]
		[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
		public SiteSettings SiteSettings
		{
			get
			{
				//if (_siteSettings == null)
				//   _siteSettings = MettleSystems.dashCommerce.Core.Caching.SiteSettingCache.GetSiteSettings();
				//return _siteSettings;
				return WebApplicationBase.SiteSettings;
			}
		}

		/// <summary>
		/// The key in labels.resx for localizing the title of this page.
		/// </summary>
		[Browsable(true), Category("Appearance"), Description("The key in labels.resx for localizing the title of this page.")]
		[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
		public string LocalizedTitleKey
		{
			get
			{
				if (_localizedTitleKey == null) {
					string filename = GetFilename();
					int dotIndex = filename.LastIndexOf(".", StringComparison.InvariantCulture);
					if (dotIndex < 0)
						dotIndex = filename.Length;
					filename = filename.Substring(0, dotIndex);
					_localizedTitleKey = "title" + System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(filename);
				}
				return _localizedTitleKey;
			}
			set { _localizedTitleKey = value; }
		}

		/// <summary>
		/// Gets the title of this page. Overrides the standard property and computes it from the site settings.
		/// <remarks>if this page has not defined a value for LocalizedTitleKey property,
		/// it will try to build a key like "title"+&lt;this page's file name&gt;</remarks>
		/// </summary>
		[Browsable(false)]
		[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
		public new virtual string Title
		{
			get
			{
				if (_bypassTitleBuild)
					return base.Title;

				return MacroSystem.Replace(SiteSettings.PageTitleTemplate);
			}
		}

		#endregion

		#region Methods

		/// <summary>
		/// Retrieves the name (and extension) of the file from which this page is compiled and parsed.
		/// </summary>
		/// <returns></returns>
		public string GetFilename()
		{
			return this.AppRelativeVirtualPath.Substring(this.AppRelativeVirtualPath.LastIndexOf("/") + 1);
		}

		public void SetTitle(string title)
		{
			base.Title = title;
			_bypassTitleBuild = true;
		}

		#endregion
	}
}
